package net.oschina.allchat.message.processing.json.parsers.core;

import net.oschina.allchat.message.processing.IElementParser;
import net.oschina.allchat.message.processing.IParser;
import net.oschina.allchat.message.processing.IParserFactory;
import net.oschina.allchat.message.processing.IParsingContext;
import net.oschina.allchat.protocol.core.Protocol;
import net.oschina.allchat.protocol.core.ProtocolException;
import net.oschina.allchat.protocol.core.stanza.Iq;
import net.oschina.allchat.protocol.core.stanza.error.BadRequest;

public class IqParserFactory implements IParserFactory<Iq> {
	private static final String VALUE_TYPE_RESULT = "result";
	private static final String VALUE_TYPE_SET = "set";
	private static final String VALUE_TYPE_GET = "get";
	private static final String VALUE_TYPE_ERROR = "error";

	@Override
	public Protocol getProtocol() {
		return Iq.PROTOCOL;
	}

	@Override
	public IParser<Iq> create() {
		return new StanzaParser<Iq>() {

			@Override
			public Iq createObject() {
				return new Iq(Iq.Type.GET);
			}

			@Override
			protected IElementParser<Iq> doGetElementParser(String parsingPath) {
				return null;
			}
			
			@Override
			protected void processType(IParsingContext<Iq> context, String value) {
				if (VALUE_TYPE_RESULT.equals(value)) {
					context.getObject().setType(Iq.Type.RESULT);
				} else if (VALUE_TYPE_SET.equals(value)) {
					context.getObject().setType(Iq.Type.SET);
				} else if (VALUE_TYPE_GET.equals(value)) {
					context.getObject().setType(Iq.Type.GET);
				} else if (VALUE_TYPE_ERROR.equals(value)) {
					context.getObject().setType(Iq.Type.ERROR);
				} else {
					throw new ProtocolException(new BadRequest(String.format("invalid iq type '%s'", value)));
				}
			}
			
			@Override
			public void processEmbeddedObject(IParsingContext<Iq> context,
					Protocol protocol, Object embedded) {
				super.processEmbeddedObject(context, protocol, embedded);
			}
		};
	}

}
